package com.onion.auth.support;

import com.onion.auth.exception.AuthException;
import com.onion.auth.support.vo.AuthUser;
import org.apache.commons.lang3.StringUtils;

public class AuthManager {

    private static AuthorizeProvider<String> authorizeProvider;

    public void setAuthorizeProvider(AuthorizeProvider<String> authorizeProvider){
        AuthManager.authorizeProvider = authorizeProvider;
    }

    /**
     * 用户登录Token
     * @param xToken
     * @param authUser
     */
    public static void loginToken(String xToken, AuthUser<String> authUser){
        authorizeProvider.cacheToken(xToken, authUser);
    }

    public static void clearToken(String xToken){
        authorizeProvider.clearToken(xToken);
    }

    /**
     * 刷新用户Token
     * @param xToken
     */
    public static void refreshToken(String xToken){
        authorizeProvider.refreshToken(xToken);
    }

    /**
     * 获取用户信息
     * @param userToken
     * @return
     */
    public static AuthUser<String> getAuthUser(String userToken){
        return authorizeProvider.getAuthUser(userToken);
    }

    /**
     * 是否拥有角色
     * @param xToken
     * @param role
     * @return
     */
    public static boolean allowRole(String xToken, String role){
        String userId = AuthManager.getUserId(xToken);
        return authorizeProvider.hasRole(userId, role);
    }

    /**
     * 是否拥有角色
     * @param userId
     * @param role
     * @return
     */
    public static boolean hasRole(String userId, String role){
        return authorizeProvider.hasRole(userId, role);
    }

    /**
     * 是否拥有权限
     * @param xToken
     * @param permission
     * @return
     */
    public static boolean allowPermission(String xToken, String permission){
        String userId = AuthManager.getUserId(xToken);
        return authorizeProvider.hasPermission(userId, permission);
    }

    /**
     * 是否拥有权限
     * @param userId
     * @param permission
     * @return
     */
    public static boolean hasPermission(String userId, String permission){
        return authorizeProvider.hasPermission(userId, permission);
    }

    /**
     * 获取拥有用户ID
     * @param xToken
     * @return
     */
    public static String getUserId(String xToken){
        AuthUser<String> authUser = authorizeProvider.getAuthUser(xToken);
        if(authUser == null){
            throw new AuthException(-5001, "未找到登陆用户:xToken=" + xToken);
        }
        if(StringUtils.isNotBlank(authUser.getUserId())){
            throw new AuthException(-5002, "用户信息异常");
        }
        return authUser.getUserId();
    }

}